package com.gxa.autoparts.admin.config;

import com.gxa.autoparts.admin.service.CountPeopleService;
import com.gxa.autoparts.core.pojo.CountPeople;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.Date;

/**
 * @author Bei
 * @date 2022/1/10 17:41
 */
@WebListener
public class OnLineCount implements HttpSessionListener {
    public static int count=0;//记录session的数量
    //监听session的创建,synchronized 防并发bug
    @Override
    public synchronized  void sessionCreated(HttpSessionEvent arg0) {
        System.out.println("【HttpSessionListener监听器】count++  增加");
        count++;
        arg0.getSession().getServletContext().setAttribute("count", count);
    }

    @Override
    @Scheduled(cron = "0 0 24 * * ?")
    public synchronized void sessionDestroyed(HttpSessionEvent arg0) {//监听session的撤销
        System.out.println("【HttpSessionListener监听器】count清零");
//        count--;
        arg0.getSession().getServletContext().setAttribute("count", 0);
    }

    @Autowired
    CountPeopleService countPeopleService;


    @Scheduled(cron = "0 15 10 * * ?")
    public void saveCount(){
        System.out.println("执行力1");
        CountPeople countPeople = new CountPeople();
        countPeople.setCount(count);
        countPeople.setDay(new Date());
        CountPeople insert = countPeopleService.insert(countPeople);
    }




}
